﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Net.NetworkInformation;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace MOTA_WP
{
    public delegate void EventCompleteDelegate(object sender, DownloadStringCompletedEventArgs e);
    public delegate void ClickDelegate(object sender, RoutedEventArgs e);
    public delegate void VoidFunctionDelegeate();

    public class WeatherItem
    {
        //屬性要與ItemTemplate中Data Binding定義的相同
        public string WeatherIcon { get; set; }
        public string WeatherStation { get; set; }
        public string temperature { get; set; }
        public string windDir { get; set; }
        public string Rainfall { get; set; }
    }

    public partial class WeatherInfoPage : PhoneApplicationPage
    {
        // Weather response data class
        public List<WeatherClass> weatherList = new List<WeatherClass>();
        // Weather data collection
        List<WeatherItem> tCollection = new List<WeatherItem>();
        // the delegate of the right side button on the top bar
        public ClickDelegate _RightClickDelegate;
        // the delegate of the back button on the top bar
        public ClickDelegate _ClickDelegate;
        public WeatherInfoPage()
        {
            InitializeComponent();
            createTopBar();
            getWeatherJson();
        }

        private void createTopBar()
        {
            _RightClickDelegate = new ClickDelegate(RefreshWeatherData);
            _ClickDelegate = new ClickDelegate(navigateBack);
            // initialize top bar
            TopBar _TopBar = new TopBar();
            _TopBar.createTopBar(backgroundCanvas, "天氣資訊", _ClickDelegate, _RightClickDelegate);
        }

        private void getWeatherJson()
        {
            lastUpdateTime();
            httpUtil _httpUtil = new httpUtil();
            EventCompleteDelegate _EventCompleteDelegate = new EventCompleteDelegate(WeatherDataReady);

            _httpUtil.sendRequest(@"http://mota.taipei.gov.tw/mota2/Weather.ashx", _EventCompleteDelegate);

        }

        public void RefreshWeatherData(object sender, RoutedEventArgs e)
        {            
            getWeatherJson();
        }

        void WeatherDataReady(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {

                // deserialize data
                DataContractJsonSerializer sir = new DataContractJsonSerializer(typeof(List<WeatherClass>));
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
                weatherList = (List<WeatherClass>)sir.ReadObject(ms);

                if (tCollection.Count != 0)
                    tCollection.Clear();

                // process json data and store it in a List(tCollection)
                foreach(WeatherClass weather in weatherList)
                {
                    WeatherItem _item = new WeatherItem();
                    int iconNum = Int32.Parse(weather.weather_icon);

                    if (iconNum != 99)
                    {
                        _item.WeatherIcon = "Images/weather_" + iconNum + ".png";       // weather icon
                    }
                    _item.WeatherStation = weather.station;                                                 // weather station
                    _item.windDir = "風向：" + weather.wind_dir;                                            // wind direction
                    _item.temperature = "氣溫：" + weather.temperature + "度";                                    // current temperature
                    _item.Rainfall = "累積雨量：" + weather.accumulated_prec + "公釐";                                //current accumulated rainfall

                    tCollection.Add(_item);
                }
            }
            else
            {
                // error handling
                MessageBox.Show("Can't get the weather date.");
            }
            
            // add weather data to ListBox (using binding)
            WeatherListBox.ItemsSource = tCollection;
            
        }

        private void navigateBack(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
        }

        private void lastUpdateTime()
        {
            System.DateTime currentTime = new System.DateTime();
            currentTime = System.DateTime.Now;
            LastUpdateTextBlock.Text = "最後更新時間：" + currentTime.Year.ToString() + @"-" 
                                        + currentTime.Month.ToString("00") + @"-" + currentTime.Day.ToString("00") 
                                        + "  " + currentTime.Hour.ToString("00") + ":" 
                                        + currentTime.Minute.ToString("00");
        }
    }
}